<template>
  <div class="personal-container">
    <div class="page-header">
      <h2 class="page-title">个人信息</h2>
    </div>

    <div class="content-wrapper">
      <!-- 左侧：用户基本信息 -->
      <div class="info-card">
        <div class="card-header">
          <h3>基本信息</h3>
        </div>
        <div class="card-body">
          <!-- 头像区域 -->
          <div class="avatar-section">
            <el-avatar :size="120" :src="userInfo.avatar ? `${BASE_IMAGE_URL}/${userInfo.avatar}` : defaultAvatar" class="user-avatar" />
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="handleAvatarUpload"
              accept="image/*"
            >
              <el-button type="primary" size="small" class="upload-btn">
                <el-icon><Upload /></el-icon>
                更换头像
              </el-button>
            </el-upload>
            <p class="avatar-tip">支持 JPG、PNG 格式，文件不超过 2MB</p>
          </div>

          <!-- 用户信息展示 -->
          <div class="info-section">
            <div class="info-item">
              <span class="info-label">用户名：</span>
              <span class="info-value">{{ userInfo.username }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">真实姓名：</span>
              <span class="info-value">{{ userInfo.realName }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">邮箱：</span>
              <span class="info-value">{{ userInfo.email }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">手机号：</span>
              <span class="info-value">{{ userInfo.phone }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">角色：</span>
              <el-tag :type="getRoleType(userInfo.roleId)" size="default">
                {{ getRoleName(userInfo.roleId) }}
              </el-tag>
            </div>
            <div class="info-item">
              <span class="info-label">创建时间：</span>
              <span class="info-value">{{ userInfo.createdTime }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：修改密码 -->
      <div class="password-card">
        <div class="card-header">
          <h3>修改密码</h3>
        </div>
        <div class="card-body">
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="100px"
            class="password-form"
          >
            <el-form-item label="旧密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                placeholder="请输入旧密码"
                show-password
                clearable
              />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                placeholder="请输入新密码（6-20位）"
                show-password
                clearable
              />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                placeholder="请再次输入新密码"
                show-password
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleUpdatePassword" :loading="passwordLoading">
                修改密码
              </el-button>
              <el-button @click="resetPasswordForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Upload } from '@element-plus/icons-vue'
import type { FormInstance, FormRules, UploadRequestOptions } from 'element-plus'
import { getCurrentUserAPI, updatePasswordAPI, uploadAvatarAPI, updateUserAPI } from '@/api/user'
import { useUserStore } from '@/stores/modules/user'

const BASE_IMAGE_URL = import.meta.env.VITE_API_BASE_URL
const userStore = useUserStore()
const id = userStore.userInfo.id
// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 用户信息接口
interface UserInfo {
  id: number
  username: string
  realName: string
  email: string
  phone: string
  roleId: number
  avatar?: string
  createdTime?: string
}

// 用户信息
const userInfo = ref<UserInfo>({
  id: 0,
  username: '',
  realName: '',
  email: '',
  phone: '',
  roleId: 4
})

// 密码表单
const passwordFormRef = ref<FormInstance>()
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})
const passwordLoading = ref(false)

// 表单验证规则
const validateConfirmPassword = (_rule: unknown, value: string, callback: (error?: Error) => void) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = reactive<FormRules>({
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为 6-20 位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ]
})

// 获取当前用户信息
const getUserInfo = async () => {
  try {
    const { data: res } = await getCurrentUserAPI(id)
    console.log('res',res)
    if (res.code === 1) {
      userInfo.value = res.data
      // 同步更新 userStore 中的用户信息
      userStore.setUserInfo(res.data)
    } else {
      ElMessage.error(res.msg || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败：', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 获取角色名称
const getRoleName = (roleId: number) => {
  const roleMap: Record<number, string> = {
    1: '管理员',
    2: '发行商',
    3: '店铺',
    4: '游客'
  }
  return roleMap[roleId] || '未知'
}

// 获取角色标签类型
const getRoleType = (roleId: number) => {
  const typeMap: Record<number, string> = {
    1: 'success',
    2: 'warning',
    3: 'primary',
    4: 'info'
  }
  return typeMap[roleId] || 'info'
}

// 头像上传前验证
const beforeAvatarUpload = (file: File) => {
  console.log('file',file)
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB！')
    return false
  }
  return true
}

// 处理头像上传
const handleAvatarUpload = async (options: UploadRequestOptions) => {
  try {
    console.log('options',options)
    const file = options.file as File
    const { data: res } = await uploadAvatarAPI(file, userInfo.value.id)

    if (res.code === 1) {
      ElMessage.success('头像上传成功')
      // 更新用户头像
      userInfo.value.avatar = res.data
      // 更新用户信息到后端
      await updateUserAPI({
        id: userInfo.value.id,
        username: userInfo.value.username,
        realName: userInfo.value.realName,
        email: userInfo.value.email,
        phone: userInfo.value.phone,
        roleId: userInfo.value.roleId,
        avatar: res.data,
        password: ''
      })
      // 刷新用户信息
      await getUserInfo()
    } else {
      ElMessage.error(res.msg || '头像上传失败')
    }
  } catch (error) {
    console.error('头像上传失败：', error)
    ElMessage.error('头像上传失败')
  }
}

// 修改密码
const handleUpdatePassword = async () => {
  if (!passwordFormRef.value) return

  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      passwordLoading.value = true
      try {
        const { data: res } = await updatePasswordAPI({
          userId: id,
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        })

        if (res.code === 1) {
          ElMessage.success('密码修改成功，请重新登录')
          // 重置表单
          resetPasswordForm()
          // 延迟跳转到登录页
          setTimeout(() => {
            // 清除用户数据
            userStore.clearUserData()
            // 跳转到登录页
            window.location.href = '/login'
          }, 1500)
        } else {
          ElMessage.error(res.msg || '密码修改失败')
        }
      } catch (error) {
        console.error('密码修改失败：', error)
        ElMessage.error('密码修改失败')
      } finally {
        passwordLoading.value = false
      }
    }
  })
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordFormRef.value?.resetFields()
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
}

// 页面加载时获取用户信息
onMounted(() => {
  getUserInfo()
})
</script>

<style scoped>
.personal-container {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ddd;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 400;
  color: #333;
}

.content-wrapper {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.info-card,
.password-card {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.card-header {
  padding: 16px 20px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #ddd;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 400;
  color: #333;
}

.card-body {
  padding: 30px;
}

/* 头像区域 */
.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-bottom: 30px;
  border-bottom: 1px solid #e5e5e5;
  margin-bottom: 30px;
}

.user-avatar {
  margin-bottom: 20px;
  border: 2px solid #ddd;
}

.upload-btn {
  margin-bottom: 10px;
}

.avatar-tip {
  margin: 0;
  font-size: 12px;
  color: #999;
}

/* 用户信息展示 */
.info-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  min-width: 100px;
  font-weight: 400;
  color: #666;
  font-size: 14px;
}

.info-value {
  color: #333;
  font-size: 14px;
}

/* 修改密码表单 */
.password-form {
  max-width: 500px;
}

:deep(.el-form-item) {
  margin-bottom: 24px;
}

:deep(.el-input__wrapper) {
  border-radius: 2px;
}

:deep(.el-button) {
  border-radius: 2px;
  padding: 10px 20px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .content-wrapper {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .personal-container {
    padding: 16px;
  }

  .page-title {
    font-size: 20px;
  }

  .card-body {
    padding: 20px;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .info-label {
    min-width: auto;
  }

  .password-form {
    max-width: 100%;
  }
}
</style>
